﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Ledict.Utility.Frm;
using Ledict.ConditionExtract.Authority;
using System.Linq;
using System.Xml;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    /// <summary>
    /// 刑事数据处理窗体（各业务考虑后期各自的特殊性，独立开） todo by zhangpeng 2016-12-14
    /// </summary>
    public partial class CrimeDataProcess : BaseForm
    {
        #region 界面初始化

        //静态锁
        private static readonly object Lock = new object();

        static CrimeDataProcess _default;
        public static CrimeDataProcess Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new CrimeDataProcess();
                        }
                    }

                }
                return _default;
            }
        }
        public CrimeDataProcess()
        {
            InitializeComponent();
            t_Case_HeadWords.TreeView.AfterExpand += new TreeViewEventHandler(t_Case_HeadWords_AfterExpand);
            t_Global_Court.TreeView.AfterExpand += new TreeViewEventHandler(t_Global_Court_AfterExpand);
            NowProcessNode.TreeView.AfterExpand += new TreeViewEventHandler(NowProcessNode_AfterExpand);
        }

        #endregion

        TreeDataBLL trbll = new TreeDataBLL();
        CaseCauseBLL casecausebLL = new CaseCauseBLL();
        Express_WordBLL wordbll = new Express_WordBLL();
        Express_AddElement addelementbll = new Express_AddElement();
        NewIDBLL newid = new NewIDBLL();
        //AboutRegexBLL regexbll = new AboutRegexBLL();
        //Ledict.Regex.BLL.Reg_RegexsBLL addreg = new Ledict.Regex.BLL.Reg_RegexsBLL();
        ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        //Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        //Express_SourceBLL SourceBLL = new Express_SourceBLL();

        //AboutRegexBLL aboutreg = new AboutRegexBLL();
        RegexParse.RegexParse getregex = new RegexParse.RegexParse();

        //ProcessDataSourceBLL datas = new ProcessDataSourceBLL();
        WorkThread_Public work = new WorkThread_Public();
        //ElementAnalyze ea = new ElementAnalyze();
        WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        //Reg_InfoRegexRelationBLL unitrelation = new Reg_InfoRegexRelationBLL();
        Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        WordBankBLL wordbankbll = new WordBankBLL();
        DataProcess_EditNode dataprocess_editnode = new DataProcess_EditNode();
        Express_MatchSituationBLL express_matchsituationbll = new Express_MatchSituationBLL();
        //案由数据表
        private static DataTable sysCaseCauseTable = new DataTable();

        WorkThread_first_Crime crimebll = new WorkThread_first_Crime();

        #region 共有变量

        private string sort = "";
        private string IsASC = "";
        private string SelectText = "";
        private string SelectWBK_ID = "";
        private TreeNode clicknode = null;
        //private TreeNode lastclicknode = null;
        private Color lastNodeFoceColor;
        //private string IsAddData = "";

        private string TypeName = "刑事罪名";
        string EW_IDText = "";
        int GridViewRowNumber = 0;

        int IsContentOrAddElement = 1;//1为编辑文本0 为编辑要素
        private string FirId = "1000";
        private List<TreeNode> NodeList = new List<TreeNode>();
        public Dictionary<string, NodeScreen> dicNodeScreen = new Dictionary<string, NodeScreen>();
        List<string> formExpress = new List<string>();
        List<string> commonExpress = new List<string>();
        Dictionary<string, List<string>> dicCommonExpress = new Dictionary<string, List<string>>();
        //public static Color cr;

        #endregion

        private void DataProcess_Load(object sender, EventArgs e)//初始化树
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            DV_AddElement.AutoGenerateColumns = false;
            DV_AddElement.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;


            //加载案由数据
            LoadSysCaseCauseData();
            // GetData("t_Case_HeadWords");
            GetData("t_Case_JudicialProcedure");
            GetData("t_Case_Property");
            GetData("t_Case_ParagraphType");

            GetData("t_Global_Court");

            //CaseCauseTree();
            CaseCauseTree_Process();


            TypeName = "刑事罪名";
            GetColor();
            //Button sendButton = (Button)sender;
            //sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
            //int i = Convert.ToInt32(Gvar.uo.m_roleList.Count<AT_Privilege>());
            //if (i > 0)
            //{
            //    foreach (AT_Privilege atp in Gvar.uo.m_roleList)
            //    {
            //        if (atp.m_privilegeAccess == "表述Right" && atp.m_privilegeOperation == 0)
            //        {
            //            Right.ReadOnly = true;
            //            wrong.ReadOnly = true;                     
            //        }
            //    }
            //}
            // textBox1.AutoWordSelection = false;
            string path = System.Environment.CurrentDirectory + @"\DataConfig.xml";
            foreach (XmlElement n in getModeListByPath(path, "config/nodeScreen"))
            {
                foreach (XmlElement item in n.ChildNodes)
                {
                    if (item.Name == "first")
                    {
                        dicNodeScreen.Add("first", new NodeScreen { Max = Convert.ToInt32(item.Attributes["max"].Value), Min = Convert.ToInt32(item.Attributes["min"].Value) });
                    }
                    else if (item.Name == "second")
                    {
                        dicNodeScreen.Add("second", new NodeScreen { Max = 0, Min = Convert.ToInt32(item.Attributes["min"].Value) });
                    }
                    else if (item.Name == "third")
                    {
                        dicNodeScreen.Add("third", new NodeScreen { Max = Convert.ToInt32(item.Attributes["max"].Value), Min = Convert.ToInt32(item.Attributes["min"].Value) });
                    }
                }
            }
            foreach (XmlElement n in getModeListByPath(path, "config/formexpress"))
            {
                string str = n.Attributes["value"].Value.ToString();
                string[] st = str.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                if (st != null && st.Length > 0)
                {
                    formExpress = st.ToList<string>();
                }
            }
            if (formExpress.Count > 0)
            {
                cmbGouZuiExtract.DataSource = formExpress;
            }
            foreach (XmlElement n in getModeListByPath(path, "config/commonexpress"))
            {
                string str = n.Attributes["value"].Value.ToString();
                string[] st = str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (st != null && st.Length > 0)
                {
                    foreach (var item in st)
                    {
                        string[] str1 = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (str1.Length == 2)
                        {
                            dicCommonExpress.Add(str1[0], str1[1].Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>());
                        }
                    }
                }
            }
        }


        #region 获取XML中某个路径下的节点信息
        /// <summary>
        /// 获取XML中某个路径下的节点信息
        /// </summary>
        /// <param name="path"></param>
        /// <param name="nodePath"></param>
        /// <returns></returns>
        static public XmlNodeList getModeListByPath(string path, string nodePath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlNodeList nodeList = doc.SelectNodes(nodePath);
            return nodeList;

        }
        #endregion
        #region 左侧树

        /// <summary>
        /// 加载案由数据
        /// </summary>
        private void LoadSysCaseCauseData()
        {
            sysCaseCauseTable = casecausebLL.GetSysCaseCauseData();
            if (sysCaseCauseTable.Rows.Count > 0)
            {
                if (sysCaseCauseTable.Select("ID in('1000','1477','2329','2415','2449') ").Length > 0)
                {
                    DataTable sysCaseCausedt = sysCaseCauseTable.Select(" ID in('1000','1477','2329','2415','2449') ").CopyToDataTable<DataRow>();
                    foreach (DataRow dr in sysCaseCausedt.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        node.Nodes.Add(new TreeNode());
                        t_Case_HeadWords.TreeView.Nodes.Add(node);
                    }
                    t_Case_HeadWords.DropDownStyle = ComboBoxStyle.DropDown;
                    t_Case_HeadWords.TreeView.AfterExpand += TreeView_AfterExpandCaseCause;
                }
            }
        }

        /// <summary>
        /// 案由数据展开节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpandCaseCause(object sender, TreeViewEventArgs e)
        {
            //e.Node.Nodes.Clear();
            //DataTable dt = new DataTable();
            //if (sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            //{
            //    dt = sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
            //    if (dt != null && dt.Rows.Count > 0)
            //    {
            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            TreeNode node = new TreeNode { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
            //            if (sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").Length > 0)
            //            {
            //                DataTable dtt = sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
            //                if (dtt != null && dtt.Rows.Count > 0)
            //                {
            //                    node.Nodes.Add(new TreeNode());
            //                }
            //            }
            //            e.Node.Nodes.Add(node);
            //        }
            //    }
            //}
        }


        public void CaseCauseTree()
        {
            #region 初始化
            this.tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";
            #endregion

            DataTable dt = trbll.GetCauseTree_Two("", 0);// 第一层

            if (dt.Rows.Count > 0)
            {
                DataRow[] arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (DataRow caseTreeNodeRode in arrayDR)
                {
                    TreeNode node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"].ToString() + "," + caseTreeNodeRode["TableName"].ToString());
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 0).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
            if (tVCaseCause.Nodes.Count > 0)
                tVCaseCause.SelectedNode = tVCaseCause.Nodes[0];
        }
        /// <summary>
        /// 显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            DataTable caseTreeNodeRode = GetChild(parentNode);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)//下级
            {

                TreeNode node = new TreeNode();

                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() + "," + caseTreeNodeRode.Rows[i]["TableName"].ToString());

                if (node.Text.Contains("（构成,认定）") && parentNode.Text == "组合")
                {
                    int k = Convert.ToInt32(express_matchsituationbll.GetExpressMatchCount(node.Tag.ToString()));
                    if (k > 0)
                        node.Text = node.Text + k;
                }

                if (clicknode != null && clicknode.FullPath != null)
                {
                    if (parentNode.FullPath.IndexOf("\\单一") > 0 || parentNode.FullPath.IndexOf("\\单一\\") > 0)
                    {
                        //DataTable dt;
                        //int ismatch = IsMatch.Checked ? 1 : 0;
                        //string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                        //string msid = expresitu.GetES_IDsByCCId(node.Tag.ToString(), ismatch, affirmIdeaResult);
                        //string msid = expresitu.GetSingleNodeMSId(node.Tag.ToString());
                        DataTable dt = wordbll.GetExpressContent(node.Tag.ToString());
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            node.ForeColor = Color.Green;
                        }
                    }
                    else if (parentNode.FullPath.IndexOf("\\组合") > 0)
                    {
                        DataTable dt = wordbll.GetExpressContent1(node.Tag.ToString());
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            node.ForeColor = Color.Green;
                        }
                        else
                        {
                            int zong = dt.Rows.Count;
                            int saiXuan = Convert.ToInt32(dt.Select("EW_Right=1").Length);
                            if (dicNodeScreen.Count > 0)
                            {
                                if (zong == 0)
                                {

                                }
                                else if (zong >= dicNodeScreen["first"].Max)
                                {
                                    if (saiXuan >= dicNodeScreen["first"].Min)
                                    {
                                        node.Text += "(完成)";
                                    }
                                    else
                                    {
                                        node.Text += "(未完成)";
                                    }
                                }
                                else if (zong < dicNodeScreen["third"].Max)
                                {
                                    if (saiXuan >= dicNodeScreen["third"].Min)
                                    {
                                        node.Text += "(完成)";
                                    }
                                    else
                                    {
                                        node.Text += "(未完成)";
                                    }
                                }
                                else if (zong >= dicNodeScreen["third"].Max && zong < dicNodeScreen["first"].Max)
                                {
                                    if (saiXuan >= dicNodeScreen["second"].Min)
                                    {
                                        node.Text += "(完成)";
                                    }
                                    else
                                    {
                                        node.Text += "(未完成)";
                                    }
                                }
                            }
                        }
                    }
                }

                if (node.Text == "组合" || GetChild(node).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                if (parentNode.Text == "组合" && node.Nodes.Count == 0)
                    continue;
                parentNode.Nodes.Add(node);
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }
            }
        }
        /// <summary>
        /// 获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            string pName = parentNode.Text;

            string[] name = parentNode.Name.Split(',');
            int ptype = Convert.ToInt32(name[0]);
            int tableName = Convert.ToInt32(name[1]);
            if (parentNode.Text == "组合")
            {
                tableName = 1;
            }
            int childType = trbll.GetChildType(pid, ptype, tableName);//下级改去哪个表查0：CaseCause 1:SYS_Express_GroupSituation
            DataTable caseTreeNodeRode;
            if (childType == 1)
            {

                if (tableName == 0) //如果是第一级 找组合单一
                {
                    int ccIsCombination = 0;
                    SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(pid);
                    if (model != null && model.CC_IsCombination == 1)
                        ccIsCombination = 1;
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab_Virtual(pid, ccIsCombination);
                    if (caseTreeNodeRode.Rows.Count == 0)
                    {
                        caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0);
                    }
                }
                else
                {
                    if (pName == "组合") //如果是组合的，去前缀
                        pid = pid.Substring(1, pid.Length - 1);
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab(pid, 0);//SYS_Express_GroupSituation 
                }
            }
            else
            {
                if (pName == "单一") //如果是组合的，去前缀
                    pid = pid.Substring(1, pid.Length - 1);
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0); //CaseCause
            }
            return caseTreeNodeRode;

        }

        /// <summary>
        /// 展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.FirstNode.Tag == null)
            //{
            e.Node.Nodes.Clear();

            CaseCauseTreeChild(e.Node);
            // }
        }

        /// <summary>
        /// 选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null)
            {
                clicknode.ForeColor = lastNodeFoceColor;
            }
            clicknode = e.Node;//保存节点
            lastNodeFoceColor = clicknode.ForeColor;
            //IsAddData = "";
            SelectText = "";
            SelectWBK_ID = "";
            if (clicknode.Text.Contains("（"))
            {
                panel_Attribute.Enabled = false;
            }
            else
            {
                panel_Attribute.Enabled = true;
            }
            dataPagerMain.ChangePageNumber(1);
            ShowRegText();
            clicknode.ForeColor = Color.Red;
            string path = clicknode.FullPath;
            if (!string.IsNullOrEmpty(path) && path.Contains("组合") && !path.EndsWith("组合"))
            {
                string str = path.Substring(path.IndexOf("组合") + 3);
                str = str.Replace("\\", "    ");

                label21.Text = str;

            }
            else
            {
                label21.Text = "";
            }
            textBox1.Text = "";
            if (clicknode.FullPath.Contains("组合") && clicknode.Text != "组合" && clicknode.Name.Split(',')[0] != "2")
            {
                SYS_Express_MatchSituation ssm = express_matchsituationbll.GetMatchSituation(clicknode.Tag.ToString());
                SYS_CaseCause sc = casecausebLL.IsParentRealation1(ssm.SituationID);
                if (dicCommonExpress.Count > 0 && sc.CC_ID!=null&& dicCommonExpress.Keys.Contains(sc.CC_ID))
                {
                    cmbChangYongExtract.DataSource = dicCommonExpress[sc.CC_ID];
                }
                else
                {
                    if (cmbChangYongExtract.Items.Count > 0)
                    {
                        cmbChangYongExtract.DataSource = null;
                        cmbChangYongExtract.Items.Clear();
                    }
                    cmbChangYongExtract.DataSource = new DataTable();
                }
            }
            else if (clicknode.Text != "单一" && clicknode.Text != "组合" && clicknode.Name.Split(',')[0] != "2")
            {
                SYS_CaseCause sc = casecausebLL.IsParentRealation1(clicknode.Tag.ToString());
                if (dicCommonExpress.Count > 0 && dicCommonExpress.Keys.Contains(sc.CC_ID))
                {
                    cmbChangYongExtract.DataSource = dicCommonExpress[sc.CC_ID];
                }
                else
                {
                    if (cmbChangYongExtract.Items.Count > 0)
                    {
                        cmbChangYongExtract.DataSource = null;
                        cmbChangYongExtract.Items.Clear();
                    }
                    cmbChangYongExtract.DataSource = new DataTable();
                }
            }
        }



        /// <summary>
        /// 是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {
            //int type = Convert.ToInt32(e.Node.Name.ToString().Split (',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
            return true;
            //}
            //return false;
        }
        #endregion

        #region 右侧信息列表
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null && clicknode.ForeColor != Color.Green)
            {
                dataGridView1.DataSource = new DataTable();
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                DataTable dt;
                string id = clicknode.Tag.ToString();
                //第一种表述节点
                //第二种原SYS_CaseCause节点
                int ismatch = IsMatch.Checked ? 1 : 0;
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                int isSingle = 1;
                if (clicknode.FullPath.IndexOf("\\组合\\") > 0) isSingle = 0;
               // string msid = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                //dt = wordbll.GetExractContent(msid, sort, IsASC, SelectText, SelectWBK_ID, 0);
                string msid = expresitu.GetSingleNodeId(id, ismatch, affirmIdeaResult);
                dt = wordbll.GetExpressContent(id, msid, isSingle, sort, IsASC, SelectText);

                //#region 此处添加此判断是为了防止已经添加打对勾的数据，再次跑的时候出现重复的，所以只保留打对勾的同样数据，未勾选的相同数据则去掉 并且不能包含caseID=1000000的 因为新加的表述caseID都为1000000的
                if (dt != null && dt.Rows.Count > 0)
                {
                    List<string> lis = new List<string>();
                    DataRow[] drs = dt.Select("EW_Right=1");
                    if (drs.Length > 0)
                    {
                        foreach (DataRow dr in drs)
                        {
                            if (!lis.Contains(dr["EW_CaseId"]) && dr["EW_CaseId"].ToString() != "1000000")
                            {
                                lis.Add(dr["EW_CaseId"].ToString());
                            }
                        }
                    }
                    if (lis.Count > 0)
                    {
                        foreach (string item in lis)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                if (dt.Rows[i]["EW_CaseId"].ToString() == item && dt.Rows[i]["EW_Right"].ToString() == "0")
                                {
                                    dt.Rows.Remove(dt.Rows[i]);
                                }
                            }
                        }

                    }
                }
                //#endregion


                if (dt.Rows.Count > 0)
                {
                    if (rbtChangGui.Checked && dt.Select("EW_UserID<>'1'").Length > 0)
                    {
                        dt = dt.Select("EW_UserID<>'1'").CopyToDataTable<DataRow>();
                    }
                    else
                    {
                        if (rbtnShaiXuan.Checked && dt.Select("EW_UserID='1'").Length > 0)
                        {
                            dt = dt.Select("EW_UserID='1'").CopyToDataTable<DataRow>();
                        }
                        else
                        {
                            dataGridView1.DataSource = new DataTable();
                            return;
                        }
                    }
                    e.TotalCount = dt.Rows.Count;
                    DataTable newdt = new DataTable();
                    lblCount.Text = dt.Select("EW_Right=1").Length.ToString();
                    newdt = dt.Clone();
                    DataRow[] dr = dt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                    for (int i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)dr[i]);
                    }
                    dataGridView1.DataSource = newdt;
                }
                else
                {
                    lblCount.Text = "0";
                    dataGridView1.DataSource = new DataTable();
                }
            }
            else
            {
                dataGridView1.DataSource = new DataTable();
            }
        }
        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ToAddWordBanks()
        {
            tabControl1.SelectTab("tabPage2");
            if (null != clicknode)
            {
                linkAddWB.Text = string.Format("<<{0}", clicknode.Text);
            }
            GetWordkeyByCCId();
        }

        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ShowRegText()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ER_Name");
            dt.Columns.Add("ER_OperateType");
            dt.Columns.Add("ER_RegexText");
            string id = clicknode.Tag.ToString();
            id = expresitu.GetES_SituationIdsById(id);
            string regCode = casecausebLL.GetRegCodeByJudgeBook(id);
            IList<Ledict.Regex.Model.Reg_Regex> reglist = getregex.GetRegexs(regCode);
            if (reglist.Count > 0)
            {
                foreach (Ledict.Regex.Model.Reg_Regex item in reglist)
                {
                    if (item != null)
                    {
                        DataRow dr = dt.NewRow();
                        dr[0] = item.ER_Name;
                        switch (item.ER_OperateType)
                        {
                            case 1:
                                dr[1] = "提取";
                                break;
                            case 2:
                                dr[1] = "替换";
                                break;
                            case 3:
                                dr[1] = "匹配";
                                break;

                        }
                        dr[2] = item.ER_RegexText;
                        dt.Rows.Add(dr);
                    }
                }

                GV_Reg.DataSource = dt;
            }
        }


        /// <summary>
        /// 转到节点树界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl1.SelectTab("tabPage1");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DV_AddElement_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)  //添加节点重跑数据
            {
                try
                {
                    OpenNodeTree();
                }
                catch (Exception error)
                {

                    MsgBox.Err("添加要素失败!");
                    Log.ErrorLog(error.Message);

                }
            }
            else if (e.ColumnIndex == 0)
            {
                // SelectText  = WhereLike.ToWherelike(DV_AddElement.Rows[e.RowIndex].Cells["Element"].Value.ToString().Replace("\r\n", ""), "EW_Content", 1);  
                SelectWBK_ID = DV_AddElement.Rows[e.RowIndex].Cells["WBK_ID"].Value.ToString();
                SelectText = "";

                dataPagerMain.ChangePageNumber(1);

            }

        }
        private void GetWordkeyByCCId()
        {
            if (clicknode != null)
            {
                string id = clicknode.Tag.ToString();

                //第一种表述节点
                //第二种原SYS_CaseCause节点
                int ismatch = IsMatch.Checked ? 1 : 0;
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                id = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                DataTable wordBankKeysdt = wordbll.GetAllwordBankKeys(id);
                DV_AddElement.DataSource = wordBankKeysdt;
            }
        }


        /// <summary>
        /// 编辑列表（单击）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //Log.WriteLog("当前选择第" + e.ColumnIndex + "列");
                #region 对勾和差
                if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
                {
                    DataGridViewCheckBoxCell checkCellRight = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Right"];
                    DataGridViewCheckBoxCell checkCellwrong = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["wrong"];
                    //Log.WriteLog("对勾框状态" + checkCellRight.Value);
                    //Log.WriteLog("错误框状态" + checkCellwrong.Value);

                    if (e.ColumnIndex == 7)
                    {
                        //if (Right.ReadOnly == true)
                        //{
                        //    //Log.WriteLog("返回");
                        //    return;
                        //}
                        if (Convert.ToBoolean(checkCellRight.Value) == true)
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                            //Log.WriteLog("返回对勾"+ checkCellRight.Value+"xx"+ checkCellwrong.Value);
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                            //Log.WriteLog("返回对勾" + checkCellRight.Value + "xx" + checkCellwrong.Value);
                        }

                    }
                    if (e.ColumnIndex == 8)
                    {
                        //if (wrong.ReadOnly == true)
                        //{
                        //    //Log.WriteLog("返回");

                        //    return;
                        //}
                        if (Convert.ToBoolean(checkCellwrong.Value) == true)
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                            //Log.WriteLog("返回对勾" + checkCellRight.Value + "xx" + checkCellwrong.Value);

                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                            //Log.WriteLog("返回对勾" + checkCellRight.Value + "xx" + checkCellwrong.Value);

                        }
                    }
                    GridViewRowNumber = e.RowIndex;
                    addData(dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString(), Convert.ToInt32(checkCellRight.Value), Convert.ToInt32(checkCellwrong.Value));

                    btnDown_Click(null, null);
                }

                #endregion
                if (e.ColumnIndex == 2)  //编辑文本
                {
                    EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                    textBox1.Text = "";
                    textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
                    //byte[] buffer = Encoding.UTF8.GetBytes(dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString());
                    //textBox1.Text = Encoding.GetEncoding("UTF-8").GetString(buffer);
                    GridViewRowNumber = e.RowIndex;
                    //ColorWord();                    
                }
            }
        }

        /// <summary>
        /// 添加到表述库加工
        /// </summary>
        /// <param name="ewID">EWID</param>
        /// <param name="cellRight">对勾框</param>
        /// <param name="cellWrong">打X框</param>
        private void addData(string ewID, int cellRight, int cellWrong)
        {
            SYS_Express_Word model = new SYS_Express_Word();
            model.EW_Right = Convert.ToInt32(cellRight);
            model.EW_Wrong = Convert.ToInt32(cellWrong);
            model.EW_ID = ewID;

            wordbll.UpdateChooseState_Process(model);
            if (model.EW_Right == 1)//添加到表述库加工
            {
                model = wordbll.GetModel_Process(ewID);

                UpdateCC_IsShowExpress(clicknode);

                if (!wordbll.Exists_Word(model))
                {
                    wordbll.Add_Word(model);//添加word 表
                }
                //检察院情形情节表述添加工具需求
                //判断当前内容是否包含已构成，如果包含，则从表里获取EW_WordPurpose为3，msid为当前数据msid的数据的EW_UseCount，
                //如果当前的EW_UseCount比较大并且和原有的caseID不同，则删除旧的数据，插入新的数据，ewid主键需要重新生成
                string[] names = new string[] { "其行为已构成", "其行为均已构成", "其行为已经构成", "被告人的行为已构成", "已构成", "构成", "公诉机关指控的事实与罪名成立", "人民检察院指控", "本院不予采纳", "不构成", "因此本案性质应当认定为" };
                foreach (var name in names)
                {
                    if (model.EW_Content.Contains(name))
                    {
                        DataTable dt = wordbll.GetMSID(model.MS_ID);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            int userCount = Convert.ToInt32(dt.Rows[0]["EW_UseCount"].ToString());
                            if (model.EW_UseCount > userCount)
                            {
                                string ewid = dt.Rows[0]["EW_ID"].ToString();
                                if (wordbll.DeleteEwID(ewid))
                                {
                                    model.EW_WordPurpose = 3;
                                    model.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                                    model.EW_Content = model.EW_Content.Substring(0, model.EW_Content.IndexOf(name)) + "。";
                                    wordbll.Add_Word(model);//添加word 表
                                    break;
                                }
                            }
                        }
                        else
                        {
                            model.EW_WordPurpose = 3;
                            model.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                            model.EW_Content = model.EW_Content.Substring(0, model.EW_Content.IndexOf(name)) + "。";
                            wordbll.Add_Word(model);//添加word 表
                            break;
                        }
                    }
                }
                
            }
            else if (model.EW_Wrong == 1)
            {
                model = wordbll.GetModel_Process(ewID);
                if (wordbll.Exists_Word(model))
                {
                    wordbll.Delete_Word(model.EW_ID);
                }
            }
        }



        /// <summary>
        /// 自己和所有父级节点记状态
        /// </summary>
        /// <param name="nowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode nowNode)
        {

            wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 1);
            if (nowNode.Parent != null)
                UpdateCC_IsShowExpress(nowNode.Parent);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Click(object sender, EventArgs e)
        {
            string DeleteID = "";
            int num = 0;
            for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要删除的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                        if (Convert.ToBoolean(check.Value) == true)
                        {
                            DeleteID = dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString();
                            if (DeleteID != "")
                            {
                                addData(DeleteID, 0, 1);
                                res = true;
                                //res = wordbll.Delete_WordProcess(DeleteID);
                            }

                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("删除成功!");
                    }
                    else
                    {
                        MsgBox.Warn("删除失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Err("删除失败!");
                    Log.ErrorLog(error.Message);

                }
                dataPagerMain.ChangePageNumber(1);
            }
        }



        /// <summary>
        /// 2017年5月15日 ljj-update 方法从未被使用
        /// 显示窗体，自动将窗体填满父窗体的工作区
        /// </summary>
        /// <param name="childForm"></param>
        //private void ShowForm(Form childForm)
        //{
        //    childForm.MdiParent = this.MdiParent;
        //    childForm.StartPosition = FormStartPosition.CenterParent;
        //    childForm.Show();
        //    childForm.Activate();
        //    childForm.Dock = DockStyle.Fill;
        //    var size = childForm.Size;
        //    var location = childForm.Location;
        //    childForm.Dock = DockStyle.None;
        //    childForm.Size = size;
        //    childForm.Location = location;
        //}
        /// <summary>
        /// 修改文本 
        /// </summary>=""
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (IsContentOrAddElement == 1)
            {
                if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
                {
                    MessageBox.Show("修改成功!");
                }
                else
                {
                    MessageBox.Show("修改失败!");
                }

                if (dataGridView1.Rows.Count > 0)
                {
                    DataGridViewCell checkCellwrong = (DataGridViewCell)dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"];
                    checkCellwrong.Value = textBox1.Text;
                    dataGridView1.Rows[GridViewRowNumber].Cells["Right"].Value = true;
                    dataGridView1.Rows[GridViewRowNumber].Cells["wrong"].Value = false;
                    addData(dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString(), 1, 0);

                    if (GridViewRowNumber < dataGridView1.Rows.Count - 1)
                    {
                        EW_IDText = dataGridView1.Rows[GridViewRowNumber + 1].Cells["EW_ID"].Value.ToString();
                        textBox1.Text = "";
                        textBox1.Text = dataGridView1.Rows[GridViewRowNumber + 1].Cells["EW_Content"].Value.ToString();
                        GridViewRowNumber = GridViewRowNumber + 1;
                        dataGridView1.ClearSelection();
                        dataGridView1.Rows[GridViewRowNumber].Selected = true;

                    }
                }
            }

        }
        #endregion

        #region 多线程

        WorkThread workObj = new WorkThread();
        //工作对象
        private Thread workThread;





        //暂停(只针对第一次加工数据)
        private void Endbtn_Click(object sender, EventArgs e)
        {
            if (workThread != null)
            {
                workThread.Abort();
                workThread = null;
            }
        }

        // 显示进度条
        public void ShowProgress(int maxCount, int currentCount)
        {
            if (this.progressBar1.InvokeRequired == false)
            {
                if (currentCount < maxCount)
                {
                    progressBar1.Value = currentCount;
                    progressBar1.Maximum = maxCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("当前{0}条|总共{1}条", currentCount, maxCount);
                }
                else if (currentCount == maxCount)
                {
                    progressBar1.Value = currentCount;
                    progressBar1.Maximum = maxCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("已完成，共{0}条", maxCount);
                    workThread = null;
                    StaticCacheBLL.plotchildDict = new Dictionary<string, DataTable>();//清除规则缓存
                }
            }
            else
            {
                ProcessShow processshow = new ProcessShow(ShowProgress);
                this.Invoke(processshow, new object[] { maxCount, currentCount });
            }

        }


        /// <summary>
        /// 开始执行线程
        /// </summary>
        private void ThreadExecute(DataSourceCondition condi, string luceneSearchType)
        {
            if (!string.IsNullOrEmpty(luceneSearchType))
            {
                //  workThread = null;
                workObj.processShow = ShowProgress;
                workObj.closeForm = CloseForm;
                workObj.conditon = condi;

                workObj.LuceneSearchType = luceneSearchType.ToUpper();//设置查询lucene方法

                //workThread = new Thread(workObj.execute_Start);
                workThread = new Thread(workObj.execute_Start);
                workThread.IsBackground = true;
                workThread.Start();
            }
        }


        #endregion

        #region  加工条件
        /// <summary>
        /// 开始加工(组织条件)第一次加工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void StartBtn_Click(object sender, EventArgs e)
        {

            try
            {
                if (t_Case_HeadWords.Text.Trim() != "" && t_Case_JudicialProcedure.Text.Trim() != "" && t_Case_Property.Text.Trim() != "" && t_Case_ParagraphType.Text.Trim() != "" && NowProcessNode.Text.Trim() != "")
                {
                    //先根据ID去获取该案由实体
                    string ccid = NowProcessNode.Text.Trim().Contains("(") ? NowProcessNode.Text.Trim().Substring(NowProcessNode.Text.IndexOf('(') + 1).Replace(")", "") : NowProcessNode.Text.Trim();
                    SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(ccid);
                    if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
                    {

                        if (workThread == null)//创建线程
                        {
                            #region 查询条件
                            //条件

                            var condi = new DataSourceCondition
                            {
                                CaseIdStart = CaseIdStart.Text.Trim(),
                                CaseIdEnd = CaseIdEnd.Text.Trim(),
                                HeadwordId = t_Case_HeadWords.Text.Trim().Substring(t_Case_HeadWords.Text.IndexOf('(') + 1).Replace(")", ""),
                                JudicialProcedureId = t_Case_JudicialProcedure.Text.Trim().Substring(t_Case_JudicialProcedure.Text.IndexOf('(') + 1).Replace(")", ""),
                                PropertyId = t_Case_Property.Text.Trim().Substring(t_Case_Property.Text.IndexOf('(') + 1).Replace(")", ""),
                                ParagraphType = t_Case_ParagraphType.Text.Trim().Substring(t_Case_ParagraphType.Text.IndexOf('(') + 1).Replace(")", ""),
                                Court = t_Global_Court.Text.Trim(),
                                SituationId = ccid,
                                SearchPerSize = int.Parse(ConfigHelper.AppSettings("LuceneSearchPerSize")) //每次查询个数
                            };

                            #endregion

                            //todo by zhangpeng:Lucene查询方法（WCF或直接通过共享方法调用）两个值：WCF，Share
                            var dataProcessType = ConfigHelper.AppSettings("LuceneSearchType");

                            if (string.IsNullOrEmpty(dataProcessType)) dataProcessType = "wcf";

                            //workObj = WorkThreadFactory.CreateWorkThreadObj(work.IsCriminal(condi.SituationId) ?
                            //       "WorkThread_first_Crime" : "WorkThread_first_People");

                            //执行刑事跑表述数据
                            workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_first_Crime");


                            //开始执行
                            ThreadExecute(condi, dataProcessType);
                        }
                        else//暂停后重启
                        {
                            MsgBox.Warn("当前操作未完成，请等待");
                            // workObj.Resume();
                        }

                    }
                    else
                    {
                        MsgBox.Warn("不存在该案由节点，请重新填写!");
                    }
                }
                else
                {
                    MsgBox.Warn(@"案由、案件性质、逻辑段、裁决程序、处理节点不可为空，请重新填写!");
                }
            }
            catch (Exception ex)
            {
                MsgBox.Err("系统报错，请查看错误!");
                Log.ErrorLog(ex.Message);
                workObj.Stop();
            }

        }

        #region  重加工
        /// <summary>
        /// 重跑数据开始(立即处理)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Start_Again(Dictionary<string, string> AddEleDic)
        {

            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");

            //NodeTree ae = NodeTree.Default;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();

            //foreach (KeyValuePair<string, string> kv in AddEleDic)//一个一个开始
            //{
            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = kv.Key;
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //Threadexecute();
        }

        /// <summary>
        /// 开始处理"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecAllStart_Click(object sender, EventArgs e)
        {
            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");
            //conditonList.Clear();

            //DataTable AllElem = addelementbll.GetAllElement();

            //for (int i = 0; i < AllElem.Rows.Count; i++)
            //{

            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = AllElem.Rows[i]["StiuatonId"].ToString();
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //// workObj

            //Threadexecute();

            ////清库
            //wordbll.UpdateClearElement_Process();
        }


        /// <summary>
        /// 保存"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="AddEleDic"></param>
        public void SaveElement(Dictionary<string, string> AddEleDic)
        {
            //ConditionExtract.NodeTree ae = ConditionExtract.NodeTree.Instance;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();
            //foreach (KeyValuePair<string, string> kv in AddEleDic)
            //{
            //    addelementbll.AddExpress_AddElement(kv.Key, kv.Value);
            //    elements.Append("," + kv.Value);
            //}

            //wordbll.UpdateAddElement_Process(EW_IDText, elements.ToString());
            //dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
        }


        #endregion

        #endregion

        #region 小功能（刷新关闭 有问题）


        bool closeState = false;
        //关闭
        private void DataProcess_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (workThread != null && workThread.IsAlive && e.CloseReason == CloseReason.UserClosing && !closeState)
            {
                workObj.Stop();

                e.Cancel = true;
            }

        }
        public void CloseForm()
        {
            if (this.progressBar1.InvokeRequired == false)
            {
                closeState = true;
                Close();
            }
            else
            {
                CloseForm closeForm = new CloseForm(CloseForm);
                this.Invoke(closeForm);
            }
        }
        //刷新
        private void button3_Click(object sender, EventArgs e)
        {
            CaseCauseTree();
        }
        #endregion

        #region 界面显示（非核心功能）

        #region 查询节点(有问题)
        DataTable Querydt;
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        private void QueryNode()
        {
            if (tVCaseCause.SelectedNode != null)
            {
                tVCaseCause.SelectedNode.ForeColor = Color.Black;
                string queryNodeName = QueryNodeTxt.Text.Trim();

                if (queryNodeName != "")
                {
                    Querydt = express_matchsituationbll.GetExpressWordData1(queryNodeName);
                    DataTable Querydt1 = express_matchsituationbll.GetExpressWordData1(FirId, queryNodeName);
                    Querydt.Merge(Querydt1);
                    StacticQuery.Text = Querydt.Rows.Count.ToString();
                    if (Querydt.Rows.Count > 0)
                    {
                        CurrNodeNum.Text = "1";
                        SumQuery.Text = CurrNodeNum.Text;
                        int currNode = Convert.ToInt32(CurrNodeNum.Text);
                        LinkIsVisible(currNode);
                        QueryNode_Page1(Querydt, currNode);
                    }
                    else
                    {
                        CurrNodeNum.Text = "0";
                        SumQuery.Text = CurrNodeNum.Text;
                        MessageBox.Show("没有查询到结果！");
                    }
                }
                else
                {
                    MessageBox.Show("请输入关键字！");
                }
            }
        }




        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrNodeNum.Text))
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page1(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }

        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrNodeNum.Text))
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page1(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
        }
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                string[] NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (int i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        FindNode(NotePidArr[i]).Expand();
                    }
                    else
                    {
                        TreeNode node = FindNode(NotePidArr[i]);
                        this.tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }


        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page1(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                string[] NotePidArr = dt.Rows[showindex - 1]["AllParentID"].ToString().Split(',');
                for (int i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i]);
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                        //FindNode(NotePidArr[i]).Expand();
                    }
                    else
                    {
                        TreeNode node = FindNode(NotePidArr[i]);
                        this.tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }
        /// <summary>
        /// 找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (TreeNode node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;

        }
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }




        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            int CurrNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= CurrNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page1(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }

        }

        #endregion

        #region 各种树菜单(案由、类型)
        public void GetData(string Tname)
        {
            DataTable dt = trbll.GetTreeHeadWords("", Tname);// 第一层
            DataRow[] arrayDR = dt.Select();

            foreach (DataRow CaseTreeNodeRode in arrayDR)
            {
                TreeNode node = new TreeNode();

                node.Text = CaseTreeNodeRode["name"].ToString() + "(" + CaseTreeNodeRode["id"].ToString() + ")";
                node.Tag = CaseTreeNodeRode["id"];

                switch (Tname)
                {
                    case "t_Case_HeadWords":
                        if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        t_Case_HeadWords.TreeView.Nodes.Add(node);
                        break;
                    case "t_Case_JudicialProcedure":
                        t_Case_JudicialProcedure.TreeView.Nodes.Add(node);
                        break;
                    case "t_Case_ParagraphType":
                        t_Case_ParagraphType.TreeView.Nodes.Add(node);
                        break;

                    case "t_Global_Court":
                        if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        t_Global_Court.TreeView.Nodes.Add(node);
                        break;

                    case "t_Case_Property":
                        t_Case_Property.TreeView.Nodes.Add(node);
                        break;

                }



            }
        }
        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            DataTable dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname);// 第一层
            DataRow[] arrayDR = dt.Select();

            //foreach (DataRow CaseTreeNodeRode in arrayDR)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]) + "(" + CaseTreeNodeRode["id"] + ")";
            //    node.Tag = CaseTreeNodeRode["id"];
            //    //判断是否有子节点
            //    if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
            //    {
            //        node.Nodes.Add(new TreeNode());
            //    }
            //    parentNode.Nodes.Add(node);

            //}
            for (int i = 0; i < arrayDR.Length; i++)
            {
                TreeNode node = new TreeNode();
                node.Text = LdFormat.ObjectToString(arrayDR[i]["name"]) + "(" + arrayDR[i]["id"] + ")";
                node.Tag = arrayDR[i]["id"];
                //判断是否有子节点
                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }

        }

        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }
        public void t_Global_Court_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Global_Court");
        }
        #endregion

        #region 刑事民事行政按钮(显示不同树)
        public void GetColor()
        {
            //button8.BackColor = Color.White;
            //button6.BackColor = Color.White;
            //button5.BackColor = Color.White;
            //button4.BackColor = Color.White;
            //button7.BackColor = Color.White;
        }
        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        #endregion

        #region 各种排序(字长、数目)

        private void SelectAdd_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 1);
            else
                SelectText = "";

            dataPagerMain.ChangePageNumber(1);
        }

        private void SelectCut_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 0);
            else
                SelectText = "";
            dataPagerMain.ChangePageNumber(1);
        }


        private void WordLengSort_Click(object sender, EventArgs e)
        {
            //sort = "WordLengSort";
            sort = "EW_WordCount";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            //sort = "AlphabetSort";
            sort = "EW_Content";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            //sort = "CountSort";
            sort = "EW_UseCount";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void ISCheckSort_Click(object sender, EventArgs e)
        {
            //sort = "RightSort";
            sort = "EW_Right";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);


        }

        private void NotCheckSort_Click(object sender, EventArgs e)
        {

        }
        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }



        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            AddWordBank();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"] != null)
            {
                AddWordBank();
                EW_IDText = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
                textBox1.Text = "";
                textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
                ColorWord();
            }
        }

        private void AddWordBank()
        {
            try
            {
                SYS_WordBank_KeyWords model = new SYS_WordBank_KeyWords();
                string addelement = textBox1.SelectedText;
                string[] wordsTextArr = addelement.Split(',', '，', ';', '；');
                foreach (var item in wordsTextArr)
                {
                    if (item != "")
                    {
                        DataTable dt = wordbankbll.GetWB_IDByHeadword(clicknode.Tag.ToString());
                        if (dt.Rows.Count > 0)
                            model.WB_ID = dt.Rows[0]["WB_ID"].ToString();
                        else
                            model.WB_ID = clicknode.Tag.ToString();
                        model.WBK_Word = item;
                        model.WBK_Length = item.Length;
                        wordbankkeywordsbll.Add(model);
                    }
                }


                MsgBox.OK("添加词库成功！");
            }
            catch (Exception error)
            {
                MsgBox.Err("添加词库失败！");
                Log.ErrorLog(error.Message);

            }

        }

        /// <summary>
        /// 标红词库
        /// </summary>
        private void ColorWord()
        {
            #region 标红词库
            //textBox1.SelectionBackColor = Color.White;

            //string EW_ID = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
            ////string MS_ID = dataGridView1.Rows[GridViewRowNumber].Cells["MS_ID"].Value.ToString();
            //IsContentOrAddElement = 1;

            //DataTable dt = express_wordbankrelbll.Get_Express_WordBankRel(EW_ID);

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    StateWord(dt.Rows[i]["WBK_Word"].ToString());

            //}

            #endregion
        }

        private void StateWord(string SelectWord)
        {

            textBox1.SelectionStart = 0;
            textBox1.SelectionLength = textBox1.Text.Length;

            System.Text.RegularExpressions.MatchCollection mc;
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(SelectWord); //定义一个Regex对象实例
            mc = r.Matches(textBox1.Text);
            for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                int start = mc[i].Index; //记录匹配字符的位置
                int length = (SelectWord).Length;
                textBox1.SelectionStart = start;
                textBox1.SelectionLength = length;
                //  textBox1.SelectionBackColor = Color.Red;
            }
        }
        #endregion

        #region 添加表述
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddExpressWprd_Click(object sender, EventArgs e)
        {
            try
            {
                string ccId = clicknode.Tag.ToString();
                string caseid = "1000000";
                string ParagraphID = "150";
                string resultText = textBox1.Text;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
                if (casecausebLL.GetSYS_CaseCauseByCCID(ccId).Rows.Count > 0)//单一节点
                {
                    DataTable processNodedt = work.BelongCaseCauseId(ccId);//节点匹配数据开始处
                    if (processNodedt.Rows.Count > 0)
                    {
                        string ewID = work.AddToExpress(resultText, caseid, ParagraphID, processNodedt.Rows[0]["CC_ID"].ToString(), ccId,new  bool[]{ true});
                        addData(ewID, 1, 0);
                    }
                    else
                    {
                        MsgBox.Warn("添加失败,未找到符合条件的根节点");
                        return;
                    }
                }
                else//组合节点
                {
                    #region 添加文本
                    SYS_Express_Word WordModel = new SYS_Express_Word();
                    WordModel.MS_ID = ccId;
                    WordModel.EW_CaseId = caseid;
                    WordModel.EW_Content = resultText;
                    WordModel.EW_UseCount = 1;
                    WordModel.EW_WordCount = resultText.Length;
                    WordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);
                    WordModel.EW_ID = wordbll.Exists_WordProcess(WordModel);
                    WordModel.EW_IsSingleExpress = 0;
                    if (WordModel.EW_ID == "")
                    {
                        WordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                        WordModel.EW_Right = 1;
                        WordModel.EW_Wrong = 0;
                        wordbll.AddWord_Process(WordModel);
                    }
                    else
                    {
                        wordbll.UpdateWord_Process(WordModel);
                    }
                    addData(WordModel.EW_ID, 1, 0);
                    #endregion

                    #region 词库
                    List<string> EW_AddElementStr = express_wordbankrelbll.WordBank("", WordModel.EW_Content);
                    foreach (var item in EW_AddElementStr)
                    {
                        if (!express_wordbankrelbll.Exists(WordModel.EW_ID, item))
                        {
                            express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), WordModel.EW_ID, item);
                        }
                    }
                    #endregion
                }
                clicknode.ForeColor = Color.Black;
                dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
                textBox1.Text = "";
                MessageBox.Show("添加表述成功！");
                //dataGridView1.Rows[GridViewRowNumber].Cells["Right"].Value = true;
                //dataGridView1.Rows[GridViewRowNumber].Cells["wrong"].Value = false;
                //addData(dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString(), 1, 0);

                //if (GridViewRowNumber < dataGridView1.Rows.Count - 1)
                //{
                //    EW_IDText = dataGridView1.Rows[GridViewRowNumber + 1].Cells["EW_ID"].Value.ToString();
                //    textBox1.Text = "";
                //    textBox1.Text = dataGridView1.Rows[GridViewRowNumber + 1].Cells["EW_Content"].Value.ToString();
                //    GridViewRowNumber = GridViewRowNumber + 1;
                //    dataGridView1.ClearSelection();
                //    dataGridView1.Rows[GridViewRowNumber].Selected = true;

                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加表述失败！");
                Log.ErrorLog(ex.ToString());
            }
        }
        #endregion



        private void button10_Click(object sender, EventArgs e)
        {
            OpenNodeTree();
        }

        private void OpenNodeTree()
        {
            if (clicknode != null)
            {
                //ConditionExtract.NodeTree nt1 = ConditionExtract.NodeTree.Instance;
                //nt1.Close();
                ConditionExtract.NodeTree nt = new ConditionExtract.NodeTree();
                ConditionExtract.NodeTree.TypeName = TypeName;
                nt.FirId = FirId;
                nt.LocateNode = expresitu.GetES_SituationIdsById(clicknode.Tag.ToString());
                nt.showRegex = true;
                if (nt.LocateNode.Contains(","))
                {
                    nt.LocateNode = nt.LocateNode.Substring(0, nt.LocateNode.IndexOf(","));
                }
            ((MainForm)this.Parent.Parent).ShowForm(nt);
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private TreeNode editnode = null;//点击获得当前节点
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            Point ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
                tVCaseCause.SelectedNode = editnode;
                //clicknode = editnode;
            }
        }
        private void 添加要素ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private void AddNodeMenuItem_Click(object sender, EventArgs e)
        {
            group_add.Visible = true;

        }


        private void btn_quit_Click(object sender, EventArgs e)
        {
            group_add.Visible = false;
            TxtCC_ID.Text = "";
            IsMatch2.Checked = true;
            IsAffirmIdeaResult2.Checked = true;
            MatchSource.Text = "0";
            AffirmIdeaSource.Text = "0";
        }

        /// <summary>
        /// 添加节点（只能在组合下添加）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            var newModel = new SYS_Express_MatchSituation();
            string ccId = TxtCC_ID.Text;
            newModel.IsMatch = IsMatch2.Checked ? 1 : 0;
            newModel.MatchSource = MatchSource.Text;
            newModel.AffirmIdeaResult = IsAffirmIdeaResult2.Checked ? "1" : "2";
            newModel.AffirmIdeaSource = AffirmIdeaSource.Text;

            string MS_ID = dataprocess_editnode.AddNode(ccId, editnode.Tag.ToString(), newModel);
            //添加完以后界面显示
            if (MS_ID != "")
            {
                MessageBox.Show("添加成功！");
                newModel = express_matchsituationbll.GetMatchSituation(MS_ID);
                clicknode.Expand();
                TreeNode addnode = new TreeNode();
                addnode.Tag = newModel.MS_ID;
                addnode.Text = newModel.SituationName;
                addnode.Name = newModel.SituationType.ToString() + ",1";
                clicknode.Nodes.Add(addnode);
            }
            else
            {
                MessageBox.Show("添加失败，节点只能在组合部分添加！");
            }
            group_add.Visible = false;
        }


        #region 情形情节树(条件)

        /// <summary>
        /// 处理节点添加树（第一级）
        /// </summary>
        public void CaseCauseTree_Process()
        {
            DataTable dt = trbll.NodeTree_Tree("");
            DataRow[] arrayDR = dt.Select("name='" + "刑事罪名" + "'");

            foreach (DataRow caseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode
                {
                    Text =
                        LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
                        LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
                    Tag = caseTreeNodeRode[0],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode[2])
                };

                FirId = caseTreeNodeRode[0].ToString();
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                NowProcessNode.TreeView.Nodes.Add(node);
            }
        }
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild_Process(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode
                {
                    Text = caseTreeNodeRode.Rows[i]["name"] + @"(" + caseTreeNodeRode.Rows[i]["id"] + @")",
                    Tag = caseTreeNodeRode.Rows[i]["id"],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"])
                };


                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }
        }

        private void NowProcessNode_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild_Process(e.Node);
        }

        #endregion

        private void GV_Reg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                OpenNodeTree();
            }
        }


        private void AgainOrganTree_Click(object sender, EventArgs e)
        {
            if (workThread == null)//创建线程
            {
                #region 查询条件

                DataSourceCondition condi = new DataSourceCondition(); //条件
                #endregion

                workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_Order");
                ThreadExecute(condi, null);

            }

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }

        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {

            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();

            //DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            //if (caseTreeNodeRode.Rows.Count == 0)
            //    return;
            //for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
            //    node.Tag = caseTreeNodeRode.Rows[i]["id"];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
            //    AllExpandNode(node.Tag.ToString());
            //}
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            string ccid = NowProcessNode.Text.Trim().Contains("(") ? NowProcessNode.Text.Trim().Substring(NowProcessNode.Text.IndexOf('(') + 1).Replace(")", "") : NowProcessNode.Text.Trim();
            SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(ccid);
            if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
            {
                if (MsgBox.Ask("是否删除" + objCaseCause.CC_Name + "(" + NowProcessNode.Text + ")" + "下的表述节点及其表述内容？") == DialogResult.Yes)
                {
                    express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim());
                    if (wordbll.DeleteSYS_Express_Word_Process(ccid) && express_matchsituationbll.DeleteSYS_Express_MatchSituation(ccid))
                    {
                        wordbll.InsertDeleteLog("SYS_Express_Word_Process", FrmLogin.userName, NowProcessNode.Text.Trim());
                        wordbll.InsertDeleteLog("SYS_Express_MatchSituation", FrmLogin.userName, NowProcessNode.Text.Trim());

                        MessageBox.Show("删除成功！");
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择处理节点！");
            }
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            // GetDataObject检索当前剪贴板上的数据 
            string str1 = Clipboard.GetText();
            textBox1.Text = str1;

            //IDataObject iData = Clipboard.GetDataObject();

            //// 将数据与指定的格式进行匹配，返回bool
            //if (iData.GetDataPresent(DataFormats.UnicodeText))
            //    // GetData检索数据并指定一个格式 
            //   textBox1.Text = (string)iData.GetData(DataFormats.UnicodeText);
            //else
            //    MessageBox.Show("目前剪贴板中数据不可转换为文本", "错误");

        }
        BackUpDataBaseBLL backUpdll = new BackUpDataBaseBLL();
        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click_1(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                //设置保存文件对话框的标题
                sfd.Title = "请选择要保存的文件路径";
                //初始化保存目录，默认exe文件目录
                sfd.InitialDirectory = Application.StartupPath;
                //设置保存文件的类型
                sfd.Filter = "备份文件|*.bak";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //获得保存文件的路径
                    string filePath = sfd.FileName;
                    //保存
                    this.Cursor = Cursors.WaitCursor;
                    backUpdll.BackUp(filePath);

                    this.Cursor = Cursors.Default;
                    MessageBox.Show("数据库备份成功！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库备份失败！错误信息：" + ex.Message);
            }
        }

        private void CrimeDataProcess_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up && e.Control)
            {
                e.Handled = true;
                btnUp_Click(null, null);
            }
            else if (e.KeyCode == Keys.Down && e.Control)
            {
                e.Handled = true;
                btnDown_Click(null, null);
            }
        }

        private void 粘贴ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            string str = string.Empty;
            // GetDataObject检索当前剪贴板上的数据 
            string str1 = Clipboard.GetText();
            textBox1.Focus();
            // textBox1.Paste();
            SendKeys.Send("^v");
            //IDataObject iData = Clipboard.GetDataObject();

            //// 将数据与指定的格式进行匹配，返回bool
            //if (iData.GetDataPresent(DataFormats.UnicodeText))
            //    // GetData检索数据并指定一个格式 
            //   textBox1.Text = (string)iData.GetData(DataFormats.UnicodeText);
            //else
            //    MessageBox.Show("目前剪贴板中数据不可转换为文本", "错误");
        }

        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (GridViewRowNumber - 1 >= 0)
            {
                dataGridView1.Focus();
                GridViewRowNumber = GridViewRowNumber - 1;
                dataGridView1.ClearSelection();
                dataGridView1.Rows[GridViewRowNumber].Selected = true;
                textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
            }
        }

        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (GridViewRowNumber + 1 <= dataGridView1.Rows.Count - 1)
            {
                dataGridView1.Focus();
                GridViewRowNumber = GridViewRowNumber + 1;
                dataGridView1.ClearSelection();
                dataGridView1.Rows[GridViewRowNumber].Selected = true;
                textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
            }
        }

        /// <summary>
        /// 构罪表述下拉框关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbGouZuiExtract_DropDownClosed(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.SelectedText))
            {
                string str = textBox1.SelectedText;
                SYS_CaseCause sc = casecausebLL.IsParentRealation1(clicknode.Tag.ToString());
                if (!string.IsNullOrEmpty(sc.CC_Name))
                {
                    textBox1.Text = textBox1.Text.Replace(str, cmbGouZuiExtract.SelectedValue.ToString().Replace("x罪", sc.CC_Name));
                }
            }
        }

        /// <summary>
        /// 常用表述下拉框关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbChangYongExtract_DropDownClosed(object sender, EventArgs e)
        {
            string str = textBox1.SelectedText;
            if (!string.IsNullOrEmpty(str))
            {
                textBox1.Text = textBox1.Text.Replace(str, cmbChangYongExtract.SelectedValue.ToString());
            }
        }
    }

    public class NodeScreen
    {
        public int Max { get; set; }
        public int Min { get; set; }
    }
}